import 'dart:io';

import 'package:cave_flutter/model/base_source_model.dart';
import 'package:cave_flutter/utils/extension/string_extension.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'package:wechat_camera_picker/wechat_camera_picker.dart';
import 'package:cave_flutter/common/common_action.dart';

import '../model/image_model.dart';
import '../style/whl_style.dart';
import '../utils/whl_dialog_util.dart';
import '../widgets/brick/widget/basic_widget.dart';
import '../widgets/brick/widget/image_widget.dart';
import '../widgets/brick/widget/text_widget.dart';

typedef CallBack(ImageModel imageModel);

typedef ListChangCallBack(List changeList);

class UploadPhotoWidget extends StatefulWidget {
  bool? canAdd = true;
  List? photoData = [];

  // bool? showName;
  bool? canDelete;
  CallBack? photoDeleteCallBack;
  ListChangCallBack? photoChangeCallBack;
  int? maxPhotoCount = 9;
  double? rowSpace = 10;
  double? columSpace = 10;
  int? columCount = 3;

  WidgetBuilder? addButtonBuilder;
  bool? onlyAdd;

  UploadPhotoWidget({
    Key? key,
    this.canAdd = true,
    this.onlyAdd = false,
    this.photoData,
    // this.showName = true,
    this.canDelete = true,
    this.photoDeleteCallBack,
    this.photoChangeCallBack,
    this.maxPhotoCount = 9,
    this.rowSpace = 10,
    this.columSpace = 10,
    this.columCount = 3,
    this.addButtonBuilder,
  }) : super(key: key);

  @override
  State<UploadPhotoWidget> createState() => _UploadPhotoWidgetState();
}

class _UploadPhotoWidgetState extends State<UploadPhotoWidget> {
  bool? canAdd = true;
  List photoData = [];

  // bool? showName;
  bool? canDelete;
  CallBack? photoDeleteCallBack;
  ListChangCallBack? photoChangeCallBack;
  int maxPhotoCount = 9;
  double rowSpace = 10;
  double columSpace = 10;
  int columCount = 3;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    canAdd = widget.canAdd;
    photoData = widget.photoData ?? [];
    // showName = widget.showName;
    canDelete = widget.canDelete;
    photoDeleteCallBack = widget.photoDeleteCallBack;
    photoChangeCallBack = widget.photoChangeCallBack;
    maxPhotoCount = widget.maxPhotoCount ?? 9;
    rowSpace = widget.rowSpace ?? 10;
    columSpace = widget.columSpace ?? 10;
    columCount = widget.columCount ?? 3;
  }

  @override
  Widget build(BuildContext context) {
    return widget.onlyAdd == true
        ? addItemWidget()
        : Container(
            color: kAppWhiteColor,
            child: GridView.builder(
              shrinkWrap: true,
              // physics: const NeverScrollableScrollPhysics(),
              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 3,
                mainAxisSpacing: 10,
                crossAxisSpacing: columSpace,
                childAspectRatio: 1.0,
              ),
              itemBuilder: (context, index) {
                if (index == photoData.length) {
                  return addItemWidget();
                }
                ImageModel model = photoData[index];
                return attachmentItemWidget(model,
                    deleteCallBack: (imageModel) {
                  WhlDialogUtil.showConfirmDialog("",
                      description: "确认要删除这张照片吗？",
                      cancelString: "取消",
                      sureString: "确认",
                      isShowCancel: true, sureAction: () {
                    deleteFile(imageModel);
                  });
                }, onTap: () {
                  // goPhotoBrowWithModel(model,logicVC.photoData,logic:logic);
                });
              },
              itemCount: photoData.length >= maxPhotoCount
                  ? photoData.length
                  : photoData.length + 1,
            ),
          );
  }

  Widget addItemWidget() {
    if (widget.addButtonBuilder != null) {
      return GestureDetector(
        onTap: () {
          WhlDialogUtil.showBottomSheet(Get.context!, ["相册", "拍照"],
              callBack: (index) async {
            if (index == 0) {
              selectPhotoAsset(Get.context!);
            } else if (index == 1) {
              takePhoto();
            }
          });
        },
        child: widget.addButtonBuilder!(context),
      );
    }
    return UIText(
        radius: 13.w,
        color: kAppColor("#F3F3F3"),
        text: "+",
        textColor: kAppWhiteColor,
        fontSize: 35.sp,
        fontWeight: FontWeight.bold,
        alignment: Alignment.center,
        onTap: () {
          WhlDialogUtil.showBottomSheet(Get.context!, ["相册", "拍照"],
              callBack: (index) async {
            if (index == 0) {
              selectPhotoAsset(Get.context!);
            } else if (index == 1) {
              takePhoto();
            }
          });
        });
  }

  Widget attachmentItemWidget(ImageModel model,
      {CallBack? deleteCallBack, Function()? onTap}) {
    return UIColumn(
      mainAxisSize: MainAxisSize.min,
      crossAxisAlignment: CrossAxisAlignment.center,
      onTap: onTap,
      clipBehavior: Clip.hardEdge,
      radius: 4,
      children: [
        Stack(
          alignment: Alignment.center,
          // clipBehavior: Clip.none,
          clipBehavior: Clip.hardEdge,
          children: [
            model.imagePath!.isNotEmpty
                ? UIImage(
                    radius: 4,
                    aspectRatio: 1.0,
                    fit: BoxFit.cover,
                    image: Image.file(
                      File(model.imagePath!),
                      fit: BoxFit.cover,
                    ),
                  )
                : UIImage(
                    aspectRatio: 1.0,
                    httpImage: model.imageUrl?.toImageUrl(),
                    fit: BoxFit.cover,
                    clipBehavior: Clip.hardEdge,
                    radius: 4,
                  ),
            if (canDelete == true && model.imageStatus == 1)
              Positioned(
                  right: 0,
                  top: 0,
                  width: 24,
                  height: 24,
                  child: UIContainer(
                    // color: kAppMainColor,
                    padding:
                        EdgeInsets.symmetric(horizontal: 2.w, vertical: 2.w),
                    width: 24,
                    height: 24,
                    onTap: () {
                      if (deleteCallBack != null) {
                        deleteCallBack(model);
                      }
                    },
                    // assetImage: "photo_delete.png",
                    child: const Icon(
                      Icons.dangerous_sharp,
                      color: Colors.white,
                    ),
                  )),
            if (model.imageStatus == 0)
              Positioned(
                left: 0,
                right: 0,
                top: 0,
                bottom: 0,
                child: UIContainer(
                  color: kAppBlackColor.withAlpha(50),
                  padding: EdgeInsets.only(top: 30.w),
                  alignment: Alignment.topCenter,
                  child: CupertinoActivityIndicator(
                    radius: 10,
                    color: kAppWhiteColor,
                  ),
                ),
              )
          ],
        ),
        // if (showName == true)
        //   UIText(
        //     textAlign: TextAlign.center,
        //     margin: const EdgeInsets.only(top: 4),
        //     text: model.name,
        //     textColor: kAppTwoTextColor,
        //     fontSize: 12.sp,
        //     shrinkWrap: false,
        //     maxLines: 2,
        //     overflow: TextOverflow.ellipsis,
        //   )
      ],
    );
  }

  Future<void> takePhoto() async {
    if (maxPhotoCount - photoData.length <= 0) {
      return;
    }
    final AssetEntity? asset = await CameraPicker.pickFromCamera(
      context,
      pickerConfig: const CameraPickerConfig(),
    );
    if (asset != null) addPhotoAssets([asset]);
  }

  Future<void> selectPhotoAsset(BuildContext context) async {
    List<AssetEntity>? asset = await AssetPicker.pickAssets(
      context,
      pickerConfig: AssetPickerConfig(
        maxAssets: maxPhotoCount - photoData.length,
        specialPickerType: SpecialPickerType.noPreview,
        textDelegate: const EnglishAssetPickerTextDelegate(),
        requestType: RequestType.image,
      ),
    );
    if (asset != null) addPhotoAssets(asset);
  }

  Future<void> addPhotoAssets(List<AssetEntity> assets) async {
    for (AssetEntity entity in assets) {
      final file = await entity.file;
      ImageModel imageModel = ImageModel(
          image: AssetEntityImageProvider(entity, isOriginal: false),
          originalImage: AssetEntityImageProvider(entity),
          imagePath: file!.path,
          assetEntity: entity,
          name: entity.title);
      uploadImageRequest(imageModel, callBack: (model, isSuccess) {
        if (isSuccess) {
          setState(() {
            imageModel.imageUrl = model.imageUrl;
            photoData.add(imageModel);
          });
          if (photoChangeCallBack != null) {
            photoChangeCallBack!(photoData);
          }
        }
      });

      // newImageModels[imageModel] = MyUploadFile(
      // path: file!.path, name: entity.title, mimeType: entity.mimeType);
    }
  }

  void deleteFile(ImageModel imageModel) {
    String filesId = imageModel.id ?? "";
    if (filesId.isNotEmpty) {
      // Api.fileDelete.post({"filesId": filesId});
    }
    photoData.remove(imageModel);
    if (photoDeleteCallBack != null) {
      photoDeleteCallBack!(imageModel);
    }
  }
}
